<template>
  <div class="search-box">
    <i class="icon-search"></i>
    <input type="text" ref='query' :value='keyword' @input="change" class='box' :placeholder='placeholder'>
    <i @click="clear" v-show="keyword" class="icon-dismiss"></i>
  </div>
</template>
<script>
  // import { debounce } from '@/common/js/dom';

  export default {
    name: 'search-box',
    props: {
      placeholder: {
        type: String,
        default: '搜索歌曲／歌手',
      },
      keyword: {
        type: String,
        default: '',
      },
    },
    methods: {
      clear() {
        this.$emit('setKeyword', '');
      },
      blur() {
        this.$refs.query.blur();
      },
      change(e) {
          const now = e.target.value.trim();
          if (now === '') {
              this.$emit('setKeyword', now);
              clearTimeout(this.timer);
              return;
          }
          this.timer && clearTimeout(this.timer);
          this.timer = setTimeout(() => {
              this.$emit('setKeyword', now.trim());
          }, 800);
      },
    },
    created() {
      this.timer = null;
    },
//    watch: {
//      keyword(now) {
//        if (now === '') {
//          this.$emit('setKeyword', now);
//          clearTimeout(this.timer);
//          return;
//        }
//        this.timer && clearTimeout(this.timer);
//        this.timer = setTimeout(() => {
//          this.$emit('setKeyword', now.trim());
//        }, 800);
//      },
//    },
  };
</script>
<style lang='stylus' scoped>
  @import '~styl/var'
  .search-box
    display flex
    align-items center
    box-sizing border-box
    width 100%
    height 40px
    padding 0 6px
    border-radius 6px
    background $color-highlight-background
    .icon-search
      font-size 24px
      color $color-background
    .box
      flex 1
      margin 0 5px
      line-height 18px
      background $color-highlight-background
      color $color-text
      font-size $font-size-medium
      &::placeholder
        color $color-text-d
    .icon-dismiss
      font-size 16px
      color $color-background
</style>
